package com.example.controller;

import com.example.service.PoetryService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//网页挂载时启用
@RestController
@CrossOrigin
public class AllPoetryController {
    @Resource
    private PoetryService poetryService;

    @GetMapping("/poetry_all/{page}/{perPage}/{flag}")//返回所有诗人
    public List<HashMap<String,Object>> poetry_all(@PathVariable int page,@PathVariable int perPage,@PathVariable int flag) {
        List ListOfHash =new ArrayList();
        if(flag==1){
            //System.out.println("返回全部诗人检索开始");
            //第一页为0
            for(int i=page*perPage+1;i<(page+1)*perPage+1;i++){
                if(i<=poetryService.count_poetry()){
                    HashMap<String,Object> hashmap=new HashMap<>();
                    hashmap.put("id",poetryService.poetry_all(i).getId()); //id作为主键 后期都以id来检索数据库！
                    hashmap.put("name",poetryService.poetry_all(i).getPoetry_name());
                    //System.out.println(poetryService.poetry_all(i).getPoetry_name());
                    hashmap.put("image",poetryService.poetry_all(i).getImage());
                    String summary=poetryService.poetry_all(i).getSummary();
                    int index=summary.indexOf("►");
                    hashmap.put("summary",summary.substring(0,index));//去除三角形后的部分
                    ListOfHash.add(hashmap);
                }
                else{
                    break;
                }
            }
        }
        else{//返回页数
            HashMap<String,Object> countmap=new HashMap<>();
            int page_num=poetryService.count_poetry()/perPage;
            if(poetryService.count_poetry()%perPage!=0){
                page_num++;
            }
            countmap.put("page_num",page_num);
            ListOfHash.add(countmap);
        }
        return ListOfHash;
    }
}
